package com.luo.demo.common.result;

import lombok.Getter;

/**
 * 统一响应结果封装类（不可变对象）
 * @param <T> 数据类型
 */
@Getter
public final class Result<T> {
    /**
     * 状态码
     */
    private final int code;

    /**
     * 响应消息
     */
    private final String message;

    /**
     * 响应数据
     */
    private final T data;

    /**
     * 时间戳（新增）
     */
    private final long timestamp;

    /**
     * 私有化构造方法
     */
    private Result(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
        this.timestamp = System.currentTimeMillis();
    }

    // ========== 成功响应 ==========

    /**
     * 成功响应（带数据）
     */
    public static <T> Result<T> success(T data) {
        return new Result<>(StatusCode.SUCCESS.getCode(), StatusCode.SUCCESS.getMessage(), data);
    }

    /**
     * 成功响应（无数据）
     */
    public static Result<Void> success() {
        return success(null);
    }

    // ========== 失败响应 ==========

    /**
     * 通用错误响应
     */
    public static Result<Void> error(StatusCode statusCode) {
        return error(statusCode, statusCode.getMessage());
    }

    /**
     * 自定义错误消息
     */
    public static Result<Void> error(StatusCode statusCode, String message) {
        return new Result<>(statusCode.getCode(), message, null);
    }

    /**
     * 完全自定义错误
     */
    public static Result<Void> error(int code, String message) {
        return new Result<>(code, message, null);
    }

    // ========== 状态码枚举 ==========

    public enum StatusCode {
        SUCCESS(200, "操作成功"),
        BAD_REQUEST(400, "请求参数错误"),
        UNAUTHORIZED(401, "未授权访问"),
        FORBIDDEN(403, "禁止访问"),
        NOT_FOUND(404, "资源不存在"),
        INTERNAL_ERROR(500, "服务器内部错误");

        private final int code;
        private final String message;

        StatusCode(int code, String message) {
            this.code = code;
            this.message = message;
        }

        public int getCode() {
            return code;
        }

        public String getMessage() {
            return message;
        }
    }

    // ========== Builder模式（可选）==========

    public static <T> Builder<T> builder() {
        return new Builder<>();
    }

    public static class Builder<T> {
        private int code;
        private String message;
        private T data;

        public Builder<T> code(int code) {
            this.code = code;
            return this;
        }

        public Builder<T> message(String message) {
            this.message = message;
            return this;
        }

        public Builder<T> data(T data) {
            this.data = data;
            return this;
        }

        public Result<T> build() {
            return new Result<>(code, message, data);
        }
    }
}
